/*
 * Copyright (C) 2009 M. Hautle.
 * 
 * This file is part of TrackedBean.
 * 
 * TrackedBean is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free
 * Software Foundation, either version 3 of the License, or (at your option) any later version.
 * 
 * TrackedBean is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
 * A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License along with TrackedBean. If not, see <http://www.gnu.org/licenses/>.
 */
package ch.trackedbean.validator.defaultValidators;

import java.lang.reflect.*;
import java.util.*;
import ch.trackedbean.validator.engine.*;

/**
 * Validator for {@link Size}.<br>
 * The {@link AbstractValidator#error} holds the following values:<br>
 * params[0]={@link Size#min()}<br>
 * params[1]={@link Size#max()}
 * 
 * @author M. Hautle
 */
public class SizeValidator extends AbstractValidator {
	/** The minimum size of the list */
	private int min;

	/** The maximum size of the list */
	private int max;

	/** If null is allowed. */
	private boolean allowNull;

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void init(Configuration cfg) {
		min = cfg.getInt(Size.ATTR_MIN, 0);
		max = cfg.getInt(Size.ATTR_MAX, Integer.MAX_VALUE);
		allowNull = cfg.getBoolean(Size.ATTR_ALLOW_NULL, false);
		final String messageKey = cfg.getString(Size.ATTR_MESSAGE, Size.DEFAULT_MESSAGE);
		error = new ErrorDescription(messageKey, new Integer(min), new Integer(max));
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	protected boolean isValid(Object value) {
		if (value == null)
			return allowNull;
		int len = -1;
		if (value instanceof Collection)
			len = ((Collection) value).size();
		else if (value instanceof Object[])
			len = Array.getLength(value);
		return len >= min && len <= max;
	}
}
